package dq.study.minimvc.paramter;

import dq.study.minimvc.annotation.MultiParam;
import dq.study.minimvc.annotation.SimpleParam;
import dq.study.minimvc.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class MultiArgumentResolver implements MethodArgumentResolver {
    @Override
    public boolean supportsParameter(Parameter parameter) {
        if (parameter.getAnnotation(MultiParam.class)!=null){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(Parameter parameter, HttpServletRequest webRequest) throws Exception {
        Class cls = parameter.getType();
        Object obj = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields){
            String methodName  = "set" + StringUtils.toUpperCaseFirstOne(field.getName());
            Method method = obj.getClass().getMethod(methodName,String.class);
            method.invoke(obj,webRequest.getParameter(field.getName()));
        }
        return obj;
    }
}
